﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Security.Principal;
using System.Web.Security;
using Yu.Cms.Common;
namespace Yu.Cms.HttpModules
{
    public class MembershipHttpModule : IHttpModule
    {
       

        /// <summary>
        ///  Initializes the NopCommerceFilter object
        /// </summary>
        /// <param name="application">The application</param>
        public void Init(HttpApplication application)
        {
            //建立安全模块   
            application.AuthenticateRequest += new EventHandler(this.Application_AuthenticateRequest);
        }


        /// <summary>
        /// 请求
        /// </summary>
        /// <param name="o"></param>
        /// <param name="e"></param>
        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {
            bool authenticated = false;
            if (HttpContext.Current.User != null && HttpContext.Current.User.Identity != null)
                authenticated = HttpContext.Current.User.Identity.IsAuthenticated;

            if (authenticated)
            {
                string cookieName = FormsAuthentication.FormsCookieName;//从验证票据获取Cookie的名字。
                //取得Cookie.
                HttpCookie authCookie = HttpContext.Current.Request.Cookies[cookieName];
                if (null == authCookie)
                {
                    return;
                }
                if (HttpContext.Current.User.Identity is FormsIdentity)
                {
                    //如果当前用户身份是FormsIdentity类即窗体验证类,此类有个属性能够访问当前用户的验证票
                    FormsIdentity fi = (FormsIdentity)HttpContext.Current.User.Identity;//创建个FormsIdentity类,用他来访问当前用户的验证票
                    //获得用户的验证票
                    FormsAuthenticationTicket ticket = fi.Ticket;
                    //从验证票中获得用户数据也就是角色数据
                    string userData = ticket.UserData;
                    //把用户数据用,分解成角色数组
                    string[] roles = userData.Split(',');
                    for (int i = 0; i < roles.Length; i++)
                    {
                        //
                        switch (roles[i])
                        {
                            case "-1":
                                roles[i] = "Administrator";
                                break;
                            default:
                                roles[i] = "User";
                                break;
                        }
                    }
                    //重写当前用户信息,就是把角色信息也加入到用户信息中
                    HttpContext.Current.User = new GenericPrincipal(fi, roles);
                }
            }           
        }




       

        public void Dispose()
        {
             
        }

        
    }
}
